//
//  HTRegisterDriverInfoVC.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/28.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTRegisterDriverInfoVC.h"
#import "HTNormalCell.h"
#import "HTAddOrderCell.h"
#import "HTRegisterLineHeader.h"
#import "HTSafeTipsCell.h"

#import "HTNormalModel.h"

#import "HTNormalTitleCell.h"
#import "HTNormalTitleModel.h"
#import "UIImageView+WebCache.h"

//选择主副驾驶
#import "HTRegisterDriverChoiceVC.h"
//输入身份证号、姓名
#import "HTInputViewController.h"

#import "HTRegisterTruckMainVC.h"
#import "HTRegisterTruckOtherVC.h"

#import "HTImageClipViewController.h"

static NSString *const userpic = @"userpic";
static NSString *const car = @"car";

@interface HTRegisterDriverInfoVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,HTInputViewControllerDelegate,HTImageClipViewControllerDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSArray *data1;
@property (nonatomic,strong) NSArray *data2;
@property (nonatomic,weak) UIImageView *headImageView;
@property (nonatomic,weak) UIImageView *driverImageView;

@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *idCard;

@property (nonatomic,strong) NSString *headImageViewUrl;
@property (nonatomic,strong) NSString *driverImageViewUrl;

@property (nonatomic,assign) NSInteger regist;
//regist :0 未认证，1认证中 2 通过 3 不通过
@end

@implementation HTRegisterDriverInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"驾驶员信息";
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
    self.regist = self.mineModel ? [self.mineModel.regist integerValue] : 0;
    [self netLoadUserMessage];
    [self configTableView];
}
- (void)configDataSource{
    self.regist = self.mineModel ? [self.mineModel.regist integerValue] : 0;
    self.data1 = @[ [HTNormalModel normalModelWithTitle:@"头像" height:80 imageUrl:self.mineModel.picurl]
                    , [HTNormalModel normalModelWithTitle:@"驾驶证" height:80 imageUrl:self.mineModel.picurl]];
    self.data2 = @[[HTNormalTitleModel normalModelWithTitle:@"姓名" detital:_mineModel.name],[HTNormalTitleModel normalModelWithTitle:@"身份证号" detital:_mineModel.carnum]];
    self.headImageViewUrl = self.mineModel.picurl;
    self.driverImageViewUrl = self.mineModel.dirverpic;
    self.name = _mineModel.name;
    self.idCard = _mineModel.carnum;
}
- (void)configTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView=[[UIView alloc]init];
    self.tableView.backgroundColor = kBackgroundColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTNormalCell" bundle:nil] forCellReuseIdentifier:normalCell];
     [self.tableView registerNib:[UINib nibWithNibName:@"HTNormalTitleCell" bundle:nil] forCellReuseIdentifier:normalTitleCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTAddOrderCell" bundle:nil] forCellReuseIdentifier:addOrderCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTSafeTipsCell" bundle:nil] forCellReuseIdentifier:safeTipsCell];
   
    
}
#pragma mark --- tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return 2;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0|indexPath.section == 1){
        return [(HTNormalModel *) self.data1[indexPath.section] height];
    }
    switch (indexPath.section) {
        case 2:
            return 50;
            break;
        case 3:
            return 100;
            break;
        case 4:
            return kWidth(60);
            break;
        default:
            break;
    }
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0)  {
        return 100;
    }
    return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 4) { //下一步
        HTAddOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:addOrderCell forIndexPath:indexPath];
        cell.backgroundColor = kBackgroundColor;
        [cell.addBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [cell.addBtn addTarget:self action:@selector(didNextBtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else if(indexPath.section == 3) {//安全提示
        HTSafeTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:safeTipsCell forIndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 2){
        HTNormalTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:normalTitleCell forIndexPath:indexPath];
        cell.normalModel = self.data2[indexPath.row];
        return cell;
    }
    HTNormalCell *cell = [tableView dequeueReusableCellWithIdentifier:normalCell forIndexPath:indexPath];
    if(indexPath.section == 0||indexPath.section == 1){
        if(indexPath.section == 0){
            cell.imageWidth.constant = 70;
            self.headImageView = cell.rightImageView;
            [self.headImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.mineModel.picurl]] placeholderImage:[UIImage imageNamed:@"bg_userpic_upload"]options:SDWebImageRefreshCached];
           
        }else{
            cell.imageWidth.constant = 90;
            self.driverImageView = cell.rightImageView;
            [self.driverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.mineModel.dirverpic]] placeholderImage:[UIImage imageNamed:@"bg_license_user"]options:SDWebImageRefreshCached];
        }
        cell.normalModel = self.data1[indexPath.section];
    }else{
        
        cell.normalModel = self.data2[indexPath.row];
    }
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        HTRegisterLineHeader *header = [[HTRegisterLineHeader alloc]initWithFrame:CGRectMake(0, 0, kHTScreenWidth, 100)];
        header.type = RegisterLineHeaderTypeOne;
        return header;
    }
    UIView *view = [[UIView alloc]initWithFrame:tableView.tableHeaderView.bounds];
    view.backgroundColor = kBackgroundColor;
    return view;
}
#pragma mark --- 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.regist == 2) {
        return;
    }
    if(indexPath.section == 2){
         HTInputViewController *input = [[HTInputViewController alloc]init];
        if(indexPath.row == 0){
            input.type = InputTypeName;
        }else{
            input.type = InputTypeCard;
        }
        input.delegate = self;
        [self.navigationController pushViewController:input animated:YES];
    }else if (indexPath.section == 0){
        [self callActionSheetWithMessage:@"请您上传真实的头像" tag:111];
    }else if(indexPath.section == 1){
        [self callActionSheetWithMessage:@"请您上传真实的驾驶证" tag:112];
    }
}
#pragma mark -- 图片处理
- (void)callActionSheetWithMessage:(NSString *)message tag:(NSInteger)tag{
    [UIAlertController actionSheetStyleShowInController:self title:@"温馨提示" message:message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        
        [alertActions addObject:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    } completion:^{
        
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if(picker.view.tag == 111){
        [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth) WithIndex:picker.view.tag withPicker:picker];
    }else if (picker.view.tag == 112){
        [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth/4*3) WithIndex:picker.view.tag withPicker:picker];
    }

}
- (void)CropImageViewControllerWithImage:(UIImage*)portraitImg Frame:(CGRect )rect WithIndex:(NSInteger )index withPicker:(UIImagePickerController *)picker {
    HTImageClipViewController *imgCropperVC = [[HTImageClipViewController alloc] initWithImage:portraitImg cropFrame:rect limitScaleRatio:3.0];
    imgCropperVC.delegate = self;
    imgCropperVC.tag = index;
    [picker pushViewController:imgCropperVC animated:NO];
}
- (void)imageCropperDidCancel:(HTImageClipViewController *)clipViewController{
    [clipViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)imageCropper:(HTImageClipViewController *)clipViewController didFinished:(UIImage *)editedImage{
    switch (clipViewController.tag) {
        case 111:
        {
            self.headImageView.image = editedImage;
            UIImage *imagenew =[self imageWithImageSimple:editedImage scaledToSize:CGSizeMake(240, 240)];
            [self netUpLoadPictureType:userpic image:imagenew];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 112:
        {
            self.driverImageView.image = editedImage;
            [self netUpLoadPictureType:car image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        default:
            break;
    }
    
}
//点击下一步
- (void)didNextBtn:(id)sender{
    if (self.regist == 0 || self.regist == 3) {//注册
        if (self.name == nil || self.name.length <= 0) {
            [HTShowUtil showMessage:@"请输入姓名"];
            return;
        }
        if (self.idCard == nil || self.idCard.length <= 0) {
            [HTShowUtil showMessage:@"请输入身份证号"];
            return;
        }
        if (self.headImageViewUrl == nil || self.headImageViewUrl.length <= 0) {
            [HTShowUtil showMessage:@"请传入头像"];
            return;
        }
        if (self.idCard == nil || self.idCard.length <= 0) {
            [HTShowUtil showMessage:@"请传入驾驶证"];
            return;
        }
        if (self.regist == 0) {
            HTRegisterDriverChoiceVC *choice = [[HTRegisterDriverChoiceVC alloc]init];
            choice.name = self.name;
            choice.idCard = self.idCard;
            [self.navigationController pushViewController:choice animated:YES];
            return;
        }
        if (self.regist == 3) {
            if ([self.mineModel.ismast isEqualToString:@"0"]) {//主驾驶
                HTRegisterTruckMainVC *main = [[HTRegisterTruckMainVC alloc]init];
                main.mineModel = self.mineModel;
                main.name = self.name;
                main.idCard = self.idCard;
                [self.navigationController pushViewController:main animated:YES];
            }else if ([self.mineModel.ismast isEqualToString:@"1"]) {//副驾驶
                HTRegisterTruckOtherVC *othe = [[HTRegisterTruckOtherVC alloc]init];
                othe.mineModel = self.mineModel;
                othe.name = self.name;
                othe.idCard = self.idCard;
                [self.navigationController pushViewController:othe animated:YES];
            }
            return;
        }
    }else{//查看消息
        if ([self.mineModel.ismast isEqualToString:@"0"]) {//主驾驶
            HTRegisterTruckMainVC *main = [[HTRegisterTruckMainVC alloc]init];
            main.mineModel = self.mineModel;
            [self.navigationController pushViewController:main animated:YES];
        }else if ([self.mineModel.ismast isEqualToString:@"1"]) {//副驾驶
            HTRegisterTruckOtherVC *othe = [[HTRegisterTruckOtherVC alloc]init];
            othe.mineModel = self.mineModel;
            [self.navigationController pushViewController:othe animated:YES];
        }
    }
  
}
    

#pragma mark --
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 100; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}

#pragma mark --- delegate
- (void)didInputMessage:(NSString *)message withType:(InputType)type{
    if (type == InputTypeName) {//姓名
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]];
        cell.detialLabel.text = message;
        self.name = cell.detialLabel.text;
    }
    if (type == InputTypeCard) {//身份证号
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:2]];
        cell.detialLabel.text = message;
        self.idCard = cell.detialLabel.text;
    }
}
#pragma mark --- 网络请求
- (void)netLoadUserMessage{
    [self startHud];
    [HTHttpRequestManager requestUserMessageSuccess:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"个人信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"获取失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"获取失败"];
            return;
        }
        self.mineModel =  [HTMineModel mj_objectWithKeyValues:responseObject[@"data"]];
        [self configDataSource];
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"获取失败"];
    }];
}

- (void)netUpLoadPictureType:(NSString *)type image:(UIImage *)image{
    [self startHud];
    [HTHttpRequestManager requestUploadPictureWithType:type image:image success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"上传图片：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return;
        }
        if ([type isEqualToString:userpic]) {
            self.headImageViewUrl = @"---";
        }else if([type isEqualToString:car]){
            self.driverImageViewUrl = @"---";
        }
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"图片保存失败"];
    }];
}
- ( UIImage *)imageWithImageSimple:( UIImage *)image scaledToSize:( CGSize )newSize

{
    UIGraphicsBeginImageContext (newSize);
    [image drawInRect : CGRectMake ( 0 , 0 ,newSize. width ,newSize. height )];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();
    UIGraphicsEndImageContext ();
    return newImage;
}

@end
